<template>
  <TableView class="role">
    <template #form>
      <NSpace justify="space-between">
        <NForm
          :show-feedback="false"
          label-placement="left"
          inline
        >
          <span style="line-height: 34px">姓名：</span>
          <NInput
            placeholder="请输入姓名"
            v-model:value="form.volunteerName"
            style="width: 150px; margin-right: 20px"
          />
          <span style="line-height: 34px">手机号：</span>
          <NInput
            placeholder="请输入手机号"
            v-model:value="form.mobilePhone"
            style="width: 150px; margin-right: 20px"
          />
          <span style="line-height: 34px">文润志愿服务联盟：</span>
          <NSelect
            :options="listOption"
            v-model:value="form.leagueId"
            placeholder="请选择联盟"
            clearable
            style="width: 150px; margin-right: 20px"
            :render-option="renderOption"
          />
          <span style="line-height: 34px">级别：</span>
          <NSelect
            :options="listZOption"
            v-model:value="form.levelCode"
            placeholder="请选择级别"
            clearable
            style="width: 150px; margin-right: 20px"
          />
          <NFormItem>
            <NButton
              type="primary"
              style="width: 78px"
              ghost
              @click="queryTableData(true)"
              :loading="tableLoading"
            >
              查询
            </NButton>
            <NButton
              style="width: 78px;margin-left: 15px;"
              @click="resetForm"
              ghost
              type="primary"
            >
              重置
            </NButton>
          </NFormItem>
        </NForm>
        <NSpace align="end">
          <NButton
            type="primary"
            style="width: 115px"
            @click="handleAdd"
          >
            新增
          </NButton>
        </NSpace>
      </NSpace>
    </template>
    <template #table="props">
      <n-data-table
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        size="small"
        :bordered="false"
        :rowKey="rowKey"
      />
    </template>
    <template #pagination>
      <NPagination
        show-size-picker
        show-quick-jumper
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
      >
        <template #suffix>页</template>
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent
      @close="modalVisible = false"
      @submit="againDelete"
      title="删除提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NModal,
  NForm,
  NFormItem,
  NSelect,
  NTag,
  NPopconfirm,
  NTooltip
} from 'naive-ui'
import { onActivated, onMounted, reactive, ref, h ,watch} from 'vue'
import { sendRequest } from '@/utils/api'
import type { preselectionModel } from '@/api/volunteer'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute, useRouter } from 'vue-router'

const message = useMessage()
const router = useRouter()
const listZOption = ref([])
const listOption = ref([])
onActivated(() => {
  console.log('window.flags.flushRole', window.flags.flushRole)
  if (window.flags.flushRole) {
    queryTableData(true)
    console.log(11)
    window.flags.flushRole = false
  }
})
const  renderOption = ({ node, option }: { node: VNode; option: SelectOption }) =>
  h(NTooltip, null, {
    trigger: () => node,
    default: () => option.label
  })
const tableData = ref<preselectionModel[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
type Reset = () => void
function useQueryForm<T = unknown>(form: T, reset: Reset): [form: T, reset: Reset] {
  return [form, reset]
}
const rowKey: any = (row: any) => row.id || ''
const modalVisible = ref(false)
const route = useRoute()
const [form, resetForm] = useQueryForm(
  reactive({
    auditFlag: null,
    leagueId: null,
    levelCode: null,
    mobilePhone: null,
    volunteerName: null
  }),
  () => {
    form.auditFlag = null
    form.leagueId = null
    form.levelCode = null
    form.mobilePhone = null
    form.volunteerName = null
  }
)
const columns: DataTableColumns<clueModel> = [
  // {
  //   type: 'selection',
  //   fixed: 'left',
  //   width: '2rem'
  // },
  {
    title: '姓名',
    key: 'name',
    width: '10rem',
    fixed: 'left',
    align: 'center'
  },
  {
    title: '手机号',
    key: 'mobilePhone',
    width: '10rem',
    align: 'center'
  },
  {
    title: '文润志愿服务联盟',
    key: 'leagueName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '性别',
    key: 'clueNumber',
    width: '10rem',
    align: 'center',
    render: (row: any) => {
      let name = '';
      row.sex == 0 ? name = '男' : name = '女'
      return h(
        NTag,
        {
          style: {
            marginRight: '6px'
          },
          type: 'info',
          bordered: false
        },
        {
          default: () => name
        }
      )
    }
  },
  {
    title: '民族',
    key: 'nation',
    width: '10rem',
    align: 'center'
  },
  {
    title: '学历',
    key: 'education',
    width: '10rem',
    align: 'center'
  },
  {
    title: '级别',
    key: 'level',
    width: '10rem',
    align: 'center'
  },
  {
    title: '审核时间',
    key: 'auditTime',
    width: '10rem',
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    width: '20rem',
    align: 'center',
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'info',
          quaternary: true,
          onClick: () => handleDetail(e)
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleEdit(e)
        },
        {
          default: () => '编辑'
        }
      ),
      h(
        NButton,
        {
          type: 'error',
          quaternary: true,
          onClick: () => handleDelete(e.id)
        },
        {
          default: () => '删除'
        }
      )
      // h(
      //   NPopconfirm,
      //   {
      //     positiveButtonProps: {
      //       size: 'tiny',
      //       color: '#007293',
      //       bordered: true,
      //     },
      //     negativeButtonProps: {
      //       size: 'tiny',
      //       color: '#007293',
      //       bordered: true,
      //     },
      //     onPositiveClick: (row: any) => {
      //       handleDelete(e.id)
      //     }
      //   },
      //   {
      //     trigger: () => {
      //       return h(
      //         NButton,
      //         {
      //           type: 'error',
      //           quaternary: true,
      //         },
      //         { default: () => '删除' }
      //       )
      //     },
      //     default: () => {
      //       return '确认删除吗？'
      //     }
      //   }
      // ),
    ]
  }
]
const tableLoading = ref(false)
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<preselectionModel>>({
    module: 'volunteer',
    api: 'volunteerList',
    override: {
      params: {
        auditFlag: form.auditFlag,
        leagueId: form.leagueId,
        levelCode: form.levelCode,
        volunteerName: form.volunteerName,
        mobilePhone: form.mobilePhone,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list
}

const handleEdit = (e: any) => {
  router.push({
    name: 'VolunteerMaterialFileEdit',
    query: { id: e.id }
  })
}

const handleDetail = (e: any) => {
  router.push({ name: 'VolunteerMaterialFileDetail', query: { id: e.id } })
}

const handleAdd = () => {
  router.push({ name: 'VolunteerMaterialFileAdd' })
}

const ids = ref()
const handleDelete = async (id: any) => {
  ids.value = id
  modalVisible.value = true
  // const [error] = await sendRequest<HttpResponse>({
  //   module: 'volunteer',
  //   api: 'volunteerDelete',
  //   override: {
  //     data: [id]
  //   }
  // })
  // if (error) return message.error(error.message)
  // message.success('删除成功')
  // queryTableData()
  // modalVisible.value = false
}
const againDelete = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'volunteer',
    api: 'volunteerDelete',
    override: {
      data: [ids.value]
    }
  })
  if (error) return message.error(error.message)
  if (res.code != 0) {
    message.error(res.data.msg)
  } else {
    message.success('删除成功')
    queryTableData(true)
    modalVisible.value = false
  }
}
//下拉
const getFunction = async () => {
  listOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'volunteer',
    api: 'leagueOptions'
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listOption.value.push({ label: i.label, value: i.value })
  })
}


//证件类型下拉
const getZFunction = async () => {
  listZOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A51'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listZOption.value.push({ label: i.dicName, value: i.dicCode })
  })
}
onMounted(() => {
  getFunction()
  getZFunction()
  queryTableData(true)
})
watch(
  () => route,
  () => {
    if (
      route.path == '/volunteer/material/file/index'
    ) {
      queryTableData(true)
    }
  },
  { deep: true, immediate: true }
)
</script>

<style lang="scss" scoped>
.role {
  padding: 29rem 20rem 42rem 30rem;
  color: rgba(0, 0, 0, 0.85);
}
</style>
